var dhxWins;
var dhxToolbar;
function doOnLoad() {
    dhxWins = new dhtmlXWindows();
    dhxWins.setImagePath(context + "/resources/dhtmlx/codebase/imgs/");
}

dhxLayout = new dhtmlXLayoutObject("parentId", "2U");
// dhxLayout.cells("a").setText("关闭");
dhxLayout.cells("a").setWidth(200);
dhxLayout.cells("a").hideHeader();
dhxLayout.cells("b").hideHeader();
dhxLayout.cells("b").setHeight(80);
//dhxLayout.cells("c").hideHeader();



dhxAccord = dhxLayout.cells("a").attachAccordion();

dhxAccord.addItem("a2", "我的通讯录");
dhxAccord.openItem("a2");
	
var toolbar = dhxAccord.cells("a2").attachToolbar();  
toolbar.setIconsPath(context + "/app/addressBook/images/");
toolbar.addButton("add", 1, "", "bar_tree_add.gif", "bar_tree_add.gif");
toolbar.addButton("edit", 2, "", "bar_tree_edit.gif", "bar_tree_edit_dis.gif");
toolbar.addButton("del", 3, "", "bar_tree_remove.gif", "bar_tree_remove_dis.gif");
toolbar.setItemToolTip("add", "添加分类");
toolbar.setItemToolTip("edit", "编辑分类");
toolbar.disableItem("edit");
toolbar.setItemToolTip("del", "删除分类");
toolbar.disableItem("del");
var action;
toolbar.attachEvent("onClick", function(id) {
			switch(id){case "add":action = "add";doCategoryAdd();
						break;
						case "edit":action = "edit";doCategoryEdit();
						break;
						case "del":action = "del";doCategoryRemove();
						break;
						}
    });


//新建添加分类窗口
function doCategoryAdd() {
    
  if(dhxWins.window("addCatWin")==null){
  	var win=dhxWins.createWindow("addCatWin",10,10,300,150);
	win.setText("添加分类");
	win.denyResize();
	win.centerOnScreen();
	win.button("park").hide();
	win.button("minmax1").hide();
	win.button("close").attachEvent("onClick",function(){
						dhxWins.window("addCatWin").setModal(false);
						dhxWins.window("addCatWin").hide();});
	win.attachObject("addCatDiv");
  	
  }  
  	document.getElementById("catName").value="";
  	document.getElementById("catId").value="";
	dhxWins.window("addCatWin").show();
	dhxWins.window("addCatWin").setModal(true);
	dhxWins.window("addCatWin").bringToTop();
	dhxWins.window("addCatWin").center();
    

}
//编辑分类
function doCategoryEdit(){
    
  if(dhxWins.window("addCatWin")==null){
  	var win=dhxWins.createWindow("addCatWin",10,10,300,150);
	win.setText("编辑分类");
	win.denyResize();
	win.centerOnScreen();
	win.button("park").hide();
	win.button("minmax1").hide();
	win.button("close").attachEvent("onClick",function(){
						dhxWins.window("addCatWin").setModal(false);
						dhxWins.window("addCatWin").hide();});
	win.attachObject("addCatDiv");
  	
  }  
  	var id = personTree.getSelectedItemId();
  	var text = personTree.getSelectedItemText();
  	document.getElementById("catName").value=text;
  	document.getElementById("catId").value=id;
	dhxWins.window("addCatWin").show();
	dhxWins.window("addCatWin").setModal(true);
	dhxWins.window("addCatWin").bringToTop();
	dhxWins.window("addCatWin").center();
    

}

//删除分类
function doCategoryRemove(){
if(confirm("确认删除?")){
	sendRequestPost();
	dhxLayout.cells("b").attachURL(context + "/app/addressBook/blank.jsp?rd="+new Date().getTime());
	
}
}

//接收服务器端相应
function outputResponse(loader) {
    if (loader.xmlDoc.responseText != null){
    	var result = loader.xmlDoc.responseText;
    	if(result != 'true'){
    		alert("添加失败");
    		 
    	}else{
    		alert("添加成功");
    	}
    } else   alert("添加失败");
    
	dhxWins.window("addCatWin").setModal(false);
	dhxWins.window("addCatWin").hide();
     personTree.deleteChildItems(0);
     personTree.loadXML(context+ "/app/addressbook.do?method=personAddressBookTree");
   
}
//接收编辑操作服务器端相应
function editOutputResponse(loader) {
    if (loader.xmlDoc.responseText != null){
    	var result = loader.xmlDoc.responseText;
    	if(result != 'true'){
    		alert("编辑失败");
    		 
    	}else{
    		alert("编辑成功");
    	}
    } else   alert("编辑失败");
    
	dhxWins.window("addCatWin").setModal(false);
	dhxWins.window("addCatWin").hide();
     personTree.deleteChildItems(0);
     personTree.loadXML(context+ "/app/addressbook.do?method=personAddressBookTree");
   
}

//接收删除操作服务器端相应
function delOutputResponse(loader) {
     personTree.deleteChildItems(0);
     personTree.loadXML(context+ "/app/addressbook.do?method=personAddressBookTree");
   
}
//发送请求
function sendRequestPost() {
	var catName = document.getElementById('catName').value;
	var catId = document.getElementById("catId").value;
	if(catName==""){
		alert("分类名称不能为空");
		return false;
	}
	switch(action){case "add":dhtmlxAjax.post(context+ "/app/addressbook.do?method=addPersonAddrBookCatgory", encodeURI('cname='+catName), outputResponse);
						break;
						case "edit":dhtmlxAjax.post(context+ "/app/addressbook.do?method=saveAddrBookCat", encodeURI('cname='+catName+'&cid='+catId), editOutputResponse);
						break;
						case "del":dhtmlxAjax.post(context+ "/app/addressbook.do?method=delAddrBookCat", encodeURI('&cid='+personTree.getSelectedItemId()), delOutputResponse);
						break;
						}

}



var subBtn = document.getElementById("subCatFormBtn");

// 如果是FF
if (subBtn.addEventListener) {
	subBtn.addEventListener('click', sendRequestPost, false);
}
// 如果是IE
else if (subBtn.attachEvent) {
	subBtn.attachEvent('onclick', sendRequestPost);
} else {
	subBtn['onclick'] = sendRequestPost;
}



personTree = dhxAccord.cells("a2").attachTree();
personTree.setImagePath(context + "/resources/dhtmlx/codebase/imgs/");
personTree.loadXML(context+ "/app/addressbook.do?method=personAddressBookTree");
personTree.setOnClickHandler(personTreeOnClick);




parent.resizeFrame(-1, 530);

function personTreeOnClick(id){
	if(id < "0"){
	toolbar.disableItem("edit");
	toolbar.disableItem("del");
		
	}else{
	toolbar.enableItem("edit");
	toolbar.enableItem("del");
	}
	dhxLayout.cells("b").detachToolbar();
	dhxToolbar = undefined;
	dhxLayout.cells("b").attachURL(context + "/app/addressbook.do?method=query&catid=" + id+"&rd="+new Date().getTime());
	//persongrid.clearAndLoad(context + "/app/addressbook.do?method=getPerAddressList&id="+id,doAfterRefresh,"json");
}

function doOnClick(itemId){
	var value = dhxToolbar.getValue('name');
	if(value != ""){
		pubgrid.clearAndLoad(context + "/app/addressbook.do?method=queryPubAddress&name="+encodeURIComponent(value)+"&rd="+new Date().getTime(),doAfterRefresh,"json");
	}
}
    



function pubTreeOnClick(id){
	if(typeof dhxToolbar == 'undefined'){
	dhxToolbar = dhxLayout.cells("b").attachToolbar();
	dhxToolbar.setIconsPath(context + "/resources/dhtmlx/codebase/imgs/");
	dhxToolbar.addText("info", 1, "姓名：");
	dhxToolbar.addInput("name", 2, "", 150);
	dhxToolbar.addButton("query", 3, "查询", "search.gif", "search.gif");
	dhxToolbar.attachEvent("onClick", doOnClick);	
	};
	
	dhxLayout.cells("b").attachObject(pubgridObj);
	var hasChild = pubTree.hasChildren(pubTree.getSelectedItemId());
	if(hasChild == 0){
		pubgrid.clearAndLoad(context + "/app/addressbook.do?method=getPubAddressList&id="+id+"&rd="+new Date().getTime(),doAfterRefresh,"json");
	}
	
}

function doAfterRefresh(){
}

//将选中的公共通讯录记录添加到个人通讯录
function addToPerson(id){
	pubgrid.selectRowById(id);
	var name = pubgrid.cells(id, 0).getValue();
	var phone = pubgrid.cells(id, 1).getValue();
	var fax = pubgrid.cells(id, 2).getValue();
	var tokenIdx = name.indexOf("^");
	name = name.substring(0,tokenIdx);
	handleInsert(name,phone,fax);
}


function handleInsert(name,phone,fax) {
	if (!dhxWins.window("addToPerWin")) {
		var obj = createNeuObj(name,phone,fax);
		if(obj==null){
		alert("请先定义个人通讯录类别，才能将公共通讯录中的联系人加入到个人通讯录");
		return;
		}else{
		var w1 = dhxWins.createWindow("addToPerWin", 50, 50, 350, 350);
		// w1.center();
		w1.centerOnScreen();
		w1.button("minmax2").hide();
		w1.button("minmax1").hide();
		w1.setText("添加至个人通讯录");
		w1.attachObject(obj);
		}
	}else{

		dhxWins.window("addToPerWin").show();
		dhxWins.window("addToPerWin").setModal(true);
		dhxWins.window("addToPerWin").bringToTop();
		dhxWins.window("addToPerWin").center();
	}

	// window.location.href = context + "/app/template.do?method=neu&tp="
	// + tp;
}

function createNeuObj(name,phone,fax) {
	var ids = personTree.getSubItems("0").split(",");
	if(personTree.getSubItems("0")=="" || personTree.getSubItems("0") ==null){
			return null;
		}
	var selectStr = "<select id=\"icatid\">";
	for (i = 0; i < ids.length; i++){
		
	 selectStr+="<option value =\""+ids[i]+"\">"+personTree.getItemText(ids[i])+"</option>" 
	
	}
	selectStr+="</select>"
	var str = "<table width=\"100%\" class=\"tab-noborder\" style=\"margin:5px;\">";
	str += "<tr>";
	str += "<td width=\"30%\">&nbsp;<b>类别</b></td><td>";
	str += selectStr;
	str += "</td></tr>";
	str += "<tr>";
	str += "<td width=\"30%\">&nbsp;<b>联系人姓名</b></td>";
	str += "<td><input type=\"text\" class=\"box3\" id=\"iname\" value=\""+name+"\"></td>";
	str += "</tr>";
	str += "<tr>";
	str += "<td width=\"30%\">&nbsp;<b>座机电话</b></td>";
	str += "<td><input type=\"input\" class=\"box3\" id=\"iphone\" value=\""+phone+"\"></td>";
	str += "</tr>";
	str += "<tr>";
	str += "<td width=\"30%\">&nbsp;<b>移动电话</b></td>";
	str += "<td><input type=\"input\" class=\"box3\" id=\"imobile\"></td>";
	str += "</tr>";
	str += "<tr>";
	str += "<td width=\"30%\">&nbsp;<b>传真</b></td>";
	str += "<td><input type=\"input\" class=\"box3\" id=\"ifax\"value=\""+fax+"\"></td>";
	str += "</tr>";
	str += "<tr>";
	str += "<td width=\"30%\">&nbsp;<b>EMAIL</b></td>";
	str += "<td><input type=\"input\" class=\"box3\" id=\"iemail\"></td>";
	str += "</tr>";
	str += "<tr>";
	str += "<td width=\"30%\">&nbsp;<b>地址</b></td>";
	str += "<td><textarea class=\"box3\" id=\"iaddress\"></textarea></td>";
	str += "</tr>";
	str += "<tr>";
	str += "<td colspan=\"2\" align=\"center\"><hr><input type=\"button\" name=\"buttont1\" class=\"button0\" value=\" 提 交 \" onclick=\"javascript:handleSubmit();\">"
			+ "&nbsp;"
			+ "&nbsp;<input type=\"button\" id=\"delbutton\" style=\"visibility:hidden;\" onclick=\"javascript:handleDelete();\" name=\"buttont1\" class=\"button0\" value=\" 删 除 \">"
			+ "</td>";
	str += "</tr>";
	str += "</table>";

	var div = document.createElement("div");
	div.innerHTML = str;

	return div;
}

//提交添加至个人通讯录表单

function handleSubmit(){	
	var catid = document.getElementById("icatid").value;
	var uname = document.getElementById("iname").value;
	var phone = document.getElementById("iphone").value;
	var fax = document.getElementById("ifax").value;
	var mobile = document.getElementById("imobile").value;
	var email = document.getElementById("iemail").value;
	var address = document.getElementById("iaddress").value;
	var params = encodeURI('userId='+userId+'&catid='+catid+'&uname='+uname+'&phone='+phone+'&fax='+fax+'&mobile='+mobile+'&email='+email+'&address='+address);
	dhtmlxAjax.post(context+ "/app/addressbook.do?method=addAddrBookAjax",params , subToPerResponse);
}

function subToPerResponse(loader){
	
if(loader.xmlDoc.responseText=="success"){
	alert("添加成功");
};
dhxWins.window("addToPerWin").setModal(false);
dhxWins.window("addToPerWin").close();
}

function submitForm() {

	myDataProcessor = new dataProcessor(context
			+ "/app/pubAddrBook.do?method=list");
	// lock feed url;
	myDataProcessor.setTransactionMode("POST", true);
	// set mode as send-all-by-post;
	myDataProcessor.setUpdateMode("off");
	// disable auto-update;
	myDataProcessor.init(mygrid);
	myDataProcessor.sendData();
	alert("send data over!");

}